package com.journey.org.ui.home.news.detail

import android.annotation.SuppressLint
import android.app.Application
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.lifecycle.viewModelScope
import com.journey.org.app.HttpManager
import com.journey.org.entity.NeteaseNewsDetailEntity
import com.mvvmhabit.org.base.BaseViewModel
import com.mvvmhabit.org.binding.command.BindingAction
import com.mvvmhabit.org.binding.command.BindingCommand
import com.mvvmhabit.org.bus.event.SingleLiveEvent
import com.mvvmhabit.org.custom.LoadingLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @Date: 2020/11/23 13:30
 * @Author:小妖
 * @Description: 新闻详情
 */
class NewsDetailViewModel(application: Application) : BaseViewModel(application) {

    val requestStateField = ObservableInt()

    val onClickAgainLoadCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            loadNeteaseNewsDetail(onNewsIdField.get()!!)
        }
    })

    val onNewsDetailField = ObservableField<NeteaseNewsDetailEntity>()

    val onNewsIdField = ObservableField<String>()

    val onNewsBodyEvent = ObservableField<String>()

    val onFinishCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            finish()
        }
    })

    @SuppressLint("CheckResult")
    fun loadNeteaseNewsDetail(id: String) {
        viewModelScope.launch(Dispatchers.Main) {
            requestStateField.set(LoadingLayout.NETWORK_LOADING)
            val map = withContext(Dispatchers.IO) {
                HttpManager.getInstance().loadNeteaseNewsDetail(id)
            }
            if (!map.isNullOrEmpty()) {
                val entity: NeteaseNewsDetailEntity = map[id]!!
                onNewsDetailField.set(entity)
                var entityContent = entity.body
                entity.img.forEach { imgItem ->
//                    var sub = entityContent.substring(0, entityContent.indexOf(imgItem.ref))
//                    val content = entityContent.substring(
//                        entityContent.indexOf(imgItem.ref),
//                        entityContent.length
//                    )
//                    sub += "<img src=\"" + imgItem.src + "\"/>"
//                    entityContent = sub + content
                    entityContent =
                        entityContent.replace(imgItem.ref, "<img src='" + imgItem.src + "'/>", true)
                }
                onNewsBodyEvent.set(entityContent)
                requestStateField.set(LoadingLayout.HIDE_LAYOUT)
            } else {
                requestStateField.set(LoadingLayout.NODATA)
                cancel()
            }
        }
    }
}